package cn.tedu.justone.pack02;

/**
 * @作者：JustOne
 * @时间：2021/8/27 - 15:04
 */
public class Demo06_案例演示多窗口售卖火车票 {
    public static void main(String[] args) {
        //综合示例：
        //用多线程模拟多个窗口售卖火车票
        //1,创建一个火车票系统类叫T12306，它有一个同步方法subTicket()。
        //2,创建一个Window类继承Thread类，可以卖票
        //3,创建5个Window对象，模拟5个窗口都在抢购T12306里面的票。

        T12306 t12306 = new T12306();
        Window w1 = new Window(t12306);
        Window w2 = new Window(t12306);
        Window w3 = new Window(t12306);
        Window w4 = new Window(t12306);
        Window w5 = new Window(t12306);
        w1.start();
        w2.start();
        w3.start();
        w4.start();
        w5.start();
    }
}

class T12306{
    private int ticket = 50;//火车票的张数

    public synchronized void subTicket(){
        Thread t = Thread.currentThread();
        if(ticket>0){
            System.out.println(t.getName() + "买到了第"+ticket+"张票，余票张数："+(ticket-1));
            ticket--;
        }else{
            try {
                System.out.println(t.getName()+"你好票已售完，过24小时再看");
                Thread.sleep(2400);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Window extends Thread{

    private T12306 t12306;

    public Window(T12306 t12306){
        this.t12306 = t12306;
    }

    @Override
    public void run() {
        while(true){
            t12306.subTicket();//买一张票
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
